﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Wyse.Server.Base
{
    /// <summary>
    /// Represetns a thread tied to a listener
    /// </summary>
    public class ListenerThread : IDisposable
    {
        /// <summary>
        /// Ctor
        /// </summary>
        public ListenerThread(Listener listener)
        {
            Listener = listener;

            mThread = new Thread(ThreadProc)
            {
                Name = listener.Name
            };
        }

        /// <summary>
        /// Thread procedure
        /// </summary>
        private void ThreadProc()
        {
            try
            {
                Listener.Start();
            }
            finally
            {
            }

            mFinishEvent.Set();
        }

        /// <summary>
        /// Starts the listener thread
        /// </summary>
        public WaitHandle Start()
        {
            mFinishEvent = new AutoResetEvent(false);

            mThread.Start();

            return mFinishEvent;
        }

        /// <summary>
        /// Stops the listener
        /// </summary>
        public void Stop()
        {
            try
            {
                Listener.Stop();
            }
            catch
            {
            }
        }

        /// <summary>
        /// Gets the associated listener
        /// </summary>
        public Listener Listener
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the listener thread's name
        /// </summary>
        public String Name
        {
            get { return Listener.Name; }
        }

        public void Dispose()
        {
            Stop();

            if (mFinishEvent != null)
            {
                mFinishEvent.Dispose();
            }
        }

        private AutoResetEvent mFinishEvent;
        private Thread mThread;
    }
}
